package com.edu.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;

import com.edu.dao.IAdminsDao;
import com.edu.entity.Admins;
import com.edu.entity.Articles;
import com.edu.entity.Users;
import com.edu.util.DBUtil;

public class AdminsDaoImpl implements IAdminsDao{

	@Override
	public List<Admins> queryAdmins() {
	    Admins admins=null;
		List<Admins> list = new ArrayList<Admins>();
		CachedRowSet crs = DBUtil.execQuery("select*from admins order by adminLevel desc");
		try {
			while (crs.next()) {
				int adminId = crs.getInt(1);
			    String adminAccount = crs.getString(2);
			    String  adminPwd = crs.getString(3);
			    String adminImg = crs.getString(4);
			    int adminLevel = crs.getInt(5);
			    admins = new Admins(adminId, adminAccount, adminPwd, adminImg, adminLevel);
			    list.add(admins);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public boolean addAdmin(Admins admins) {
		return DBUtil.executeUpdate("insert into admins values(null,?,?,?,1)", admins.getAdminAccount(),admins.getAdminPwd(),admins.getAdminImg());
	}

	@Override
	public Admins queryAdminsByNameandPwd(String adminAccount, String adminPwd) {
		Admins admins=null;
		CachedRowSet crs = DBUtil.execQuery("select*from admins where adminAccount=? and adminPwd=? ", adminAccount,adminPwd);
		try {
			while (crs.next()) {
				int adminId = crs.getInt(1);
			    String adminAccount1 = crs.getString(2);
			    String  adminPwd1 = crs.getString(3);
			    String adminImg = crs.getString(4);
			    int adminLevel = crs.getInt(5);
			    admins = new Admins(adminId, adminAccount1, adminPwd1, adminImg, adminLevel);
			    
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return admins;
	}

	@Override
	public boolean logoutAdmin(int adminId) {
		// TODO Auto-generated method stub
		return DBUtil.executeUpdate("update admins set adminLevel = 0 where adminId=?", adminId);
	}

	@Override
	public boolean startAdmin(int adminId) {
		// TODO Auto-generated method stub
		return DBUtil.executeUpdate("update admins set adminLevel = 1 where adminId=?", adminId);
	}

	@Override
	public int countAdmins() {
		String sql="select count(*) from admins where adminLevel=1";
		CachedRowSet crs = DBUtil.execQuery(sql);
		int count=0;
		try {
			while (crs.next()) {
				int sum=crs.getInt(1);	
				count=sum;
			}
		} catch (SQLException e) {	
			e.printStackTrace();
		}
		return count;
	}

	
	
}
